package com.abhishekduhoon.tfis;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class Methods {
	
	public static String reformSequence (String userSequence){
		userSequence = userSequence.replaceAll("[^ATGC]" , "");
		return userSequence;
	}
	
	 public static String insertCode(String sequence, String insert, int index) {
		 String sequenceBegin = sequence.substring(0 , index);
		 String sequenceEnd = sequence.substring(index);
		 return sequenceBegin + insert + sequenceEnd;
	 }
	 
	 public static double[][] pfmConversion(double[][] positionWeightMatrix, int transcriptionFactorLength){
		 double totalSequences = positionWeightMatrix[0][0] + positionWeightMatrix[1][0] + positionWeightMatrix[2][0] + positionWeightMatrix[3][0] + 0.8;
		 for(int i = 0; i < 4; i++){
			 for(int j = 0; j < transcriptionFactorLength; j++){
				 positionWeightMatrix[i][j] = Math.log((((positionWeightMatrix[i][j] + 0.2)/totalSequences)/0.25))/Math.log(2);
			 }
		 }
		 return positionWeightMatrix;
	 }
	 
	 public static double thresholdCalculator(double[][] positionWeightMatrix, int transcriptionFactorLength, int percent){
		 double threshold = 0;
	     double temp;
	     for(int i = 0; i < transcriptionFactorLength; i++){
	    	 temp = 0;
	    	 for(int j = 0; j < 4; j++){
	    		 if(positionWeightMatrix[j][i] > temp){
	    			 temp = positionWeightMatrix[j][i];
	    		 }
	    	 }  
	    	 threshold = threshold + temp;
	     }
	     threshold=(percent*threshold)/100;
	     return threshold;
	 }
	 
	 public static boolean checkOccurence(double threshold, double[][] positionWeightMatrix, int transcriptionFactorLength, int sequenceLength,String sequence){
		 double score;
		 int position;
		 char base;
		 for(int i = 0; i <= sequenceLength- transcriptionFactorLength; i++){
			 score = 0;
			 position = 0;
			 for(int j = i; j < i + transcriptionFactorLength; j++){
				 base = sequence.charAt(j);
				 if(base == 'A'){
					 score = score + positionWeightMatrix[0][position];
				 }
				 else if(base == 'C'){
					 score = score + positionWeightMatrix[1][position];
				 }
				 else if(base == 'G'){
					 score = score + positionWeightMatrix[2][position];
	             }
	             else{
	            	 score=score+positionWeightMatrix[3][position];
	             }
				 position++;
			 }
	         if(score >= threshold){
	            return true;
	         }
		 }
		 return false; 
	 }
	 
	 public static String getAccession(String gi){
		 String accession = "";
		 try {
			 URL url = new URL("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id="+gi+"&rettype=acc");
			 BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
			 accession = br.readLine();
			 br.close();
		 }
		 catch (MalformedURLException e) {
	            System.out.println("Malformed URL: " + e.getMessage());
	     	}
	     catch (IOException e) {
	            System.out.println("I/O Error: " + e.getMessage());
	        }
	       return accession;  
	 }
	 
	 public static String getReq(String accession){
		 String req = "";
		 try {
			 URL url = new URL("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=nucleotide&term="+accession+"[accn]&usehistory=y");
	         BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
	         String line;
	         while ((line = br.readLine()) != null) {
	        	 req = req + line;
	           	}
	         br.close();    
	        }
	        catch (MalformedURLException e) {
	            System.out.println("Malformed URL: " + e.getMessage());
	        }
	        catch (IOException e) {
	            System.out.println("I/O Error: " + e.getMessage());
	        }
	      return req;  
	 }
	 
	 public static String getFasta(String req){
		 String fasta = "";
		 int a=req.indexOf("<QueryKey>");
         int b=req.indexOf("</QueryKey>");
         int c=req.indexOf("<WebEnv>");
         int d=req.indexOf("</WebEnv>");
         String key=req.substring(a + 10, b);
         String web=req.substring(c + 8, d);
         try {
        	 URL url = new URL("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&query_key="+key+"&WebEnv="+web+"&rettype=fasta&retmode=text");
        	 BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
        	 fasta = br.readLine();
        	 fasta = fasta + "|";
        	 String line;
        	 while ((line = br.readLine()) != null) {
        		 fasta = fasta + line;
        	 }
        	 br.close();
         }
         catch (MalformedURLException e) {
        	 System.out.println("Malformed URL: " + e.getMessage());
         }
         catch (IOException e) {
        	 System.out.println("I/O Error: " + e.getMessage());
         } 
         return fasta;
	 }
	 
	 public static String[] multipleSequences(String userSequence){
		 String delimiter = "[> ]";
	     String[] sequences = userSequence.split(delimiter);
	     return sequences;
	 }

}
